<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}项目`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="产品选择" prop="productId">
        <el-select v-model="drawerProps.row!.productId" placeholder="请选择产品" clearable>
          <el-option v-for="item in productList" :key="item.id" :label="item.productName" :value="item.id as string" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="projectStart">
        <el-date-picker
          v-model="drawerProps.row!.projectStart"
          type="datetime"
          placeholder="选择开始时间"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="projectEnd">
        <el-date-picker
          v-model="drawerProps.row!.projectEnd"
          type="datetime"
          placeholder="选择结束时间"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="ProjectDrawer">
import { ref, onMounted } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { Project } from "@/api/interface";
import axios from "axios";
const baseUrl = import.meta.env.VITE_BASE_URL;
const emit = defineEmits(["submit"]);

const productList = ref();
// 添加当前用户状态
const currentUser = ref("");

// 在组件挂载时获取当前用户
onMounted(async () => {
  const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
  if (userInfo.userName) {
    currentUser.value = userInfo.userName;
  }
  await initFormData();
});

const initFormData = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
    const userId = Number(userInfo.id) || 0; // 如果没有 id，则使用默认值 0
    //数据库
    const response = await axios.post(baseUrl + "/api/carbon/getAllProducts", {
      userId: userId
    });
    if (response.data && response.data.code === 200) {
      productList.value = response.data.data;
      console.log("响应数据_读取产品列表:", productList.value);
    } else {
      // 处理后端返回的错误信息
      const errorMsg = response.data.msg || "获取产品列表失败";
      console.error("获取产品列表错误:", errorMsg);
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    console.error("获取产品列表出错:", error);
    ElMessage.error("获取产品列表失败，可能是因为参数错误或网络问题");
  }
};

const rules: FormRules = {
  productId: [{ required: true, message: "请选择产品", trigger: "change" }],
  projectStart: [{ required: true, message: "请选择开始时间", trigger: "change" }],
  projectEnd: [{ required: true, message: "请选择结束时间", trigger: "change" }]
};

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Project.ResProject>;
  userName?: string;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {},
  userName: ""
});

// 接收父组件传来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
    const userId = Number(userInfo.id) || 0; // 如果没有 id，则使用默认值 0
    console.log("当前用户ID:", userId);
    console.log("提交的项目数据:", drawerProps.value.row);
    //数据库
    const response = await axios.post(baseUrl + "/api/carbon/createNewProject", {
      productId: drawerProps.value.row!.productId,
      projectStart: drawerProps.value.row!.projectStart,
      projectEnd: drawerProps.value.row!.projectEnd,
      userId: userId
    });
    console.log("新增项目接口返回：", response.data);
    if (response.data && response.data.code === 200) {
      emit("submit");
      ElMessage.success({ message: `${drawerProps.value.title}项目成功！` });
      drawerVisible.value = false;
    } else {
      // 处理后端返回的错误信息
      const errorMsg = response.data.msg || "新增项目失败";
      console.error("新增项目错误:", errorMsg);
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    console.error("新增项目出错:", error);
    ElMessage.error("新增项目失败，可能是因为参数错误或网络问题");
  }
};

defineExpose({
  acceptParams
});
</script>
